import { useEffect, useState } from "react";
import { MeshStandardMaterial } from "three";
import { EcctrlJoystick } from "./stick";

export default function Joystick() {
  const [isTouchScreen, setIsTouchScreen] = useState(false);
  const [isLandscape, setIsLandscape] = useState(false); // 是否横屏

  useEffect(() => {
    if ("ontouchstart" in window || navigator.maxTouchPoints > 0) {
      setIsTouchScreen(true);
    } else {
      setIsTouchScreen(false);
    }
    eventListen();
    // 清理事件监听
    return () => {
      window.removeEventListener("orientationchange", orientationChange);
      window.removeEventListener("resize", orientationChange);
    };
  }, []);

  function eventListen() {
    if ("onorientationchange" in window) {
      window.addEventListener("orientationchange", orientationChange);
    }
    window.addEventListener("resize", orientationChange);
  }
  function orientationChange() {
    setIsLandscape(window.innerWidth > window.innerHeight);
  }

  return (
    isTouchScreen && (
      <EcctrlJoystick
        joystickPositionLeft={
          (isLandscape ? "75%" : "50%") as unknown as number
        }
        joystickPositionBottom={-20}
        // 摇杆基座材质
        joystickBaseProps={{
          material: new MeshStandardMaterial({
            color: "white",
            transparent: true,
            opacity: 0.5,
          }),
        }}
        // 摇杆柄材质
        joystickStickProps={{
          material: new MeshStandardMaterial({
            color: "white",
            transparent: true,
            opacity: 0.8,
          }),
        }}
        // 摇杆材质
        joystickHandleProps={{
          material: new MeshStandardMaterial({
            color: "white",
            emissive: "white",
            emissiveIntensity: 1,
          }),
        }}
      >
        <ambientLight intensity={10} />
      </EcctrlJoystick>
    )
  );
}
